package xyz.thoughtset.viewer.modules.ds.http.simple.linker;


import lombok.SneakyThrows;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import xyz.thoughtset.viewer.common.connector.entity.bo.ConnectorMeta;
import xyz.thoughtset.viewer.common.connector.entity.bo.Linker;
import xyz.thoughtset.viewer.common.core.constants.FolderNameConstant;
import xyz.thoughtset.viewer.modules.ds.http.core.linker.HttpConnBuilder;
import xyz.thoughtset.viewer.modules.ds.http.simple.interceptor.SelfInterceptorLoad;

import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;
import java.util.Properties;

//@Component
public class ManualHttpReqBuilder extends HttpConnBuilder {
    public ManualHttpReqBuilder(Linker dataLinker) {
        super(dataLinker);
    }

    @SneakyThrows
    @Override
    protected OkHttpClient.Builder addInterceptor(OkHttpClient.Builder builder,
                                                  ConnectorMeta connectorMeta, Properties properties) {
        URLClassLoader urlClassLoader = new URLClassLoader(
                new URL[]{new URL(FolderNameConstant.jarFileAllPath(dataLinker.getJarFilePath()))},
                Thread.currentThread().getContextClassLoader());
        Class clazz = urlClassLoader.loadClass(dataLinker.getDriverClassName());
        SelfInterceptorLoad interceptor = (SelfInterceptorLoad) clazz.newInstance();
        List<Interceptor> interceptors = interceptor.buildInterceptors(
                connectorMeta.getUrl(),
                connectorMeta.getAk(),
                connectorMeta.getSk(),
                properties);
        if (interceptors != null && !interceptors.isEmpty()) {
            for (Interceptor interceptorEle : interceptors) {
                builder.addInterceptor(interceptorEle);
            }
        }
        return builder;
    }
}
